import React, { Component } from 'react';
import Head from 'next/head';
import { message,Tag,Badge,Icon,Tooltip,Row,Col,Spin,Skeleton,Popover } from 'antd';
import Highlight from 'react-highlight'
import MyLayout from '../../components/layout';
import Comment from '../../components/comment';
// import UserCard from '../../components/userCard';
import UserCard from '../../components/userCard/index2';
import { time } from '../../utils'
import * as API from '../../api/api'
import {getJwt} from '../../lib/auth'
import './index.less';

export default class Article extends Component {
    constructor() {
        super();
        this.state = {
            isFollow:false,
            isLike:false,
            isCollect:false,
            likeNum:0,      //点赞数
            commentNum:0,   //回复数
            collectNum:0,
            author:{},      //作者信息
            loadingAuthor:false,
            commentUsers:{},  //评论用户
            userCounts:[],   //用户评论数
        }
    }

    static async getInitialProps({req,query,reduxStore}) {
        const { id } = query;
        let token = getJwt({req});
        let res = await API.getArticleDetail({id,token});
        let resData = res.data;
        let articleData = resData.data;
        let {isFollow,isLike,isCollect } = resData;
        return {articleData,isFollow,isLike,isCollect,articleId:id}; 
    }


    componentWillMount() {
        const { articleData = {},isFollow,isLike,isCollect } = this.props;
        const {like_count,pv_count,collection_count,comment_count} = articleData;
        this.setState({
            isFollow,
            isLike,
            isCollect,
            likeNum:like_count,
            commentNum:comment_count,
            collectNum:collection_count
        })
        this.getAuthorInfo()
        this.getCommentUsers()
    }
    updateCommentNum=(num)=>{
        this.setState({
            commentNum:num
        })
    }
    //获取作者信息
    getAuthorInfo(){
        this.setState({
            loadingAuthor:true
        })
        let {author} = this.props.articleData;
        API.batchGetUsersInfo({userIds:author._id}).then(res => {
            if (res.data.code === 1) {
                let data = res.data.data;
                this.setState({
                    author:data[author._id],
                    loadingAuthor:false
                })
            } 
        })
    }
    //获取评论用户
    getCommentUsers(){
        let {articleId} = this.props;
        API.getCommentUsers(articleId).then(res => {
            if (res.data.code === 1) {
                let {users,counts} = res.data.data;
                this.setState({
                    commentUsers:users,
                    userCounts:counts
                })
            } 
        })
    }
    toggleLike = () => {
        let {articleId} = this.props;
        API.toggleLike(articleId).then(res => {
            if (res.data.code === 1) {
                this.setState({
                    isLike:res.data.isLike,
                    likeNum:res.data.count,
                })
                message.success(res.data.message);
            } 
        })
    }
    toggleCollect = () => {
        let {articleId} = this.props;
        API.toggleCollect(articleId).then(res => {
            if (res.data.code === 1) {
                this.setState({
                    isCollect:res.data.isCollect,
                    collectNum:res.data.count,
                })
                message.success(res.data.message);
            } 
        })
    }
    //关注
    toggleFollow=()=>{
        let {author} = this.state;
        let {articleData} = this.props;
        let userId = articleData.author._id;
        API.toggleFollow(userId).then(res => {
            if (res.data.code === 1) {
                let {isFollow,count} = res.data;
                this.updateUserFollow({
                    isFollow,
                    count,
                    userId
                })
                // isFollow?follower_count++:follower_count--
                // this.setState({
                //     isFollow,
                //     author:Object.assign({},author,{follower_count:count})
                // })
            }
        })
    }

    updateUserFollow=(params)=>{
        let {isFollow,count,userId} = params;
        let {author,commentUsers} = this.state;
        if(commentUsers[userId]){
            commentUsers[userId].is_follow = isFollow;
            commentUsers[userId].follower_count = count;
            this.setState({
                commentUsers:JSON.parse(JSON.stringify(commentUsers))      
            })
        }
        if(userId == author._id){
            this.setState({
                isFollow,
                author:Object.assign({},author,{follower_count:count})
            })
        }
    }

    openComment = () =>{
        this.refs.Comment.openControl()
    }
    render() {
        let {articleData={},articleId} = this.props;
        let {isLike,likeNum,isCollect,isFollow,commentNum,collectNum,author,loadingAuthor,commentUsers,userCounts} = this.state;
        return (
            <MyLayout showBg={true}>
                <div className="container">
                    <Head>
                        <title>{articleData.title}</title>
                    </Head>
                    <div className="leftFixed_tools">
                        <a className="tool_btn" onClick={this.toggleLike}>
                            <Badge count={likeNum}>
                               {isLike? 
                               <Tooltip title="已赞"><Icon type="like" theme="filled" style={{fontSize: 20,}}/></Tooltip>:
                               <Tooltip title="喜欢就点赞把"><Icon type="like" style={{fontSize: 20}}/>
                               </Tooltip>}
                            </Badge>
                        </a>
                        <a className="tool_btn" onClick={this.toggleCollect}>
                            <Badge count={collectNum} >
                                {isCollect?<Tooltip title="已收藏">
                                <Icon type="star" theme="filled" style={{fontSize: 20}}/></Tooltip>:<Tooltip title="点击收藏">
                                <Icon type="star-o" style={{fontSize: 20}}/>
                                </Tooltip>}
                            </Badge>
                        </a>  
                        <a className="tool_btn" onClick={this.openComment}>
                            <Badge count={commentNum} >
                                <Icon type="message"  style={{fontSize: 20}}/> 
                            </Badge>
                        </a>
                    </div>
                    <div className="view">
                        <Row gutter={16}>
                            <Col md={17}>
                                <div className="panel_card">
                                    <div className="article">
                                        <div className="article_head">
                                            <h1 className="title">{articleData.title}</h1>
                                            {/* <div className="author_block">
                                                <a href="" className="author_link">
                                                    <img src={articleData.author.avatar} alt={articleData.author_name}/>
                                                </a>
                                                <div className="author_info">
                                                    <a className="author_name" href="">
                                                        {articleData.author_name}
                                                    </a>
                                                    <div className="article_count">
                                                        <Tooltip title={'最后编辑于'+time(articleData.update_time,'YYYY-MM-DD HH:mm:ss')}>
                                                            <span>{time(articleData.create_time,'LL')}</span> 
                                                        </Tooltip>
                                                        <span>浏览：{articleData.pv_count}</span>
                                                        <span>回复：{commentNum}</span>
                                                    </div>
                                                </div>
                                            </div> */}
                                           
                                            <div className="article_info">
                                                <Tooltip title={'最后编辑于'+time(articleData.update_time,'YYYY-MM-DD HH:mm:ss')}><span>发布于 {time(articleData.create_time)}</span> </Tooltip>
                                                <span> 作者：</span>
                                                <span>{articleData.author_name}</span>
                                                {/* <span> {isFollow?(<Tag onClick={this.toggleFollow}>已关注</Tag>):(<Tooltip title="关注作者可以查看更多的文章"><Tag onClick={this.toggleFollow} color="red">关注</Tag></Tooltip>)}</span> */}
                                            </div>
                                        </div>
                                        <div className="article_body">
                                            <div className="markdown-body">
                                                <Highlight innerHTML={true}>
                                                    {articleData.content}
                                                </Highlight>
                                            </div>
                                        </div>
                                        {/* <div className="like_collect">
                                            <Badge count={likeNum}>
                                                <a onClick={this.toggleLike}>{isLike? <Tooltip title="已赞"><Icon type="heart" style={{fontSize: 20,color:'red'}}/></Tooltip>:<Tooltip title="喜欢就点赞把"><Icon type="heart-o" style={{fontSize: 20,color:'red'}}/></Tooltip>}</a>  
                                            </Badge>
                                            <Badge count={collectNum}>
                                                <a onClick={this.toggleCollect}>{isCollect?<Tooltip title="已收藏"><Icon type="star" style={{fontSize: 20,color:'red'}}/></Tooltip>:<Tooltip title="点击收藏"><Icon type="star-o" style={{fontSize: 20,color:'red'}}/></Tooltip>}</a>  
                                            </Badge>
                                        </div> */}
                                    </div>
                                    <ul className="clearfix articleMeta">
                                        <li>
                                            <span>{articleData.pv_count}</span>
                                            <div className="meta_title">浏览</div>
                                        </li>
                                        <li>
                                            <span>{commentNum}</span>
                                            <div className="meta_title">回复</div>
                                        </li>
                                    </ul>
                                    {/*评论用户  */}
                                    <div className="comment_users">
                                        <h3>评论用户</h3>
                                        {
                                           
                                           userCounts.map((item) => {
                                                return (
                                                    <Popover key={item.userId} placement="bottom" content={
                                                    <UserCard updateFollow={this.updateUserFollow} commentCount={item.count} user={commentUsers[item.userId]} />}>
                                                        <a className="user" key={item.userId}>
                                                            <img width="32" height="32" className="avatar" src={commentUsers[item.userId].avatar} alt={commentUsers[item.userId].username}/>
                                                            {
                                                                item.count>1?(<span className="count">{item.count}</span>):null
                                                            }
                                                        </a>
                                                    </Popover> 
                                                )
                                            })
                                        }    
                                    </div>
                                    <div id="comment">
                                        {
                                            articleData.allow_comment === true ?
                                                (<Comment
                                                    ref="Comment"
                                                    authorId={articleData.author._id}
                                                    articleId={articleId} 
                                                    updateCommentNum={this.updateCommentNum}/>) 
                                                    : <div className="not_allow_cmt">该文章暂时无法评论</div>
                                        }
                                    </div>
                                </div>
                            </Col>
                            <Col md={7} >
                                <div className="right_aside">
                                    
                                    {/* <Spin  spinning={loadingAuthor} indicator={<Icon type="loading" style={{ fontSize: 24 }} spin />}>  */}
                                        <div className="panel_card">
                                            <div className="card_hedaer">
                                                <div className="card_title">关于作者</div>
                                            </div>
                                            <div className="card_body">
                                                <Skeleton className="card_section" loading={loadingAuthor} avatar active>
                                                <div className="card_section">
                                                    <div className="author_block">
                                                        <a href="" className="author_link">
                                                            <img src={author.avatar} alt={author.username}/>
                                                        </a>
                                                        <div className="author_info">
                                                            <a className="author_name" href="">
                                                                {author.username}
                                                            </a>
                                                            <div className="author_signature">
                                                                {author.signature?author.signature:'这个人很懒什么也没留下'}
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div className="card_section">
                                                    <div className="author_counts">
                                                        <div className="number_box">
                                                            <a className="number_item" href="">
                                                                <div className="number_item_name">文章</div>
                                                                <strong className="number_item_value">{author.article_count}</strong>
                                                            </a>
                                                            <a className="number_item" href="">
                                                                <div className="number_item_name">关注者</div>
                                                                <strong className="number_item_value">{author.follower_count}</strong>
                                                            </a>
                                                            <a className="number_item" href="">
                                                                <div className="number_item_name">评论了</div>
                                                                <strong className="number_item_value">{author.comment_count}</strong>
                                                            </a>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div className="card_section">
                                                    <div className="following">
                                                        <button className={isFollow?'btn active':'btn'} onClick={this.toggleFollow}>
                                                            {isFollow?'已关注':(<span><Icon type="plus" /> 关注</span> )} 
                                                        </button>
                                                    </div>
                                                </div>
                                                </Skeleton>
                                            </div>
                                        </div>   
                                    {/* </Spin>     */}
                                </div>
                            </Col>
                        </Row>
                    </div>
                </div>
            </MyLayout>                        
        );
    }
}

